﻿using Consul;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;

namespace ClientDemo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // 服务发现
            List<string> targets = FindServiceEndpoints("OrderService");
            foreach (var item in targets)
            {
                Console.WriteLine(item);
            }
            List<string> targets1 = FindServiceEndpoints("ProductService");
            foreach (var item in targets1)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
        static List<string> FindServiceEndpoints(string serviceName)
        {
            var _client = new ConsulClient(config =>
            {
                var uriBuilder = new UriBuilder("http://localhost:8500");
                config.Address = uriBuilder.Uri;
            });
            var targets = new List<string>();
            try
            {
                var r = _client.Health.Service(serviceName, "", true).Result;
                if (r.StatusCode != HttpStatusCode.OK)
                    throw new ApplicationException($"query consul server error");
                targets = r.Response.Select(x => $"{x.Service.Address}:{x.Service.Port}").ToList();
            }
            catch { }
            return targets;
        }
    }
}
